<!-- 广告管理 -->
<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import { getAdPage, updateAd, deleteAd } from "@/api/ad";
import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/role";

import { AdForm, AdQuery, AdPageVO } from "@/api/ad/types";
import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";
import Editor from "@/components/WangEditor/index.vue";
import MultiUpload from "@/components/Upload/MultiUpload.vue";
import { readConfigFile } from "typescript";

const queryFormRef = ref(ElForm); // 查询表单
const adFormRef = ref(ElForm); // 广告表单
const uploadRef = ref<UploadInstance>(); // 上传组件
const dateTimeRange = ref("");
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除广告ID集合 用于批量删除
const queryParams = reactive<AdQuery>({
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0); // 数据总数
const pageData = ref<AdPageVO[]>(); // 广告分页数据
const deptList = ref<OptionType[]>(); // 部门下拉数据源
const roleList = ref<OptionType[]>(); // 角色下拉数据源

const listData = ref([""]);
const showViewer = ref(false);

function getImg(imgUrl: any) {
  listData.value = [];
  listData.value.push(imgUrl);
  showViewer.value = true;
}

function closeViewer() {
  showViewer.value = false;
}

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  } else {
    queryParams.startTime = "";
    queryParams.endTime = "";
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 广告表单数据
const formData = reactive<AdForm>({
  status: "1",
  remark: "",
});

const formUserData = reactive<AdForm>({
  status: "1",
  loginName: "",
});

const opType = ref(0);
// 广告导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  username: [{ required: true, message: "广告名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "广告昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "广告角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getAdPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  广告表单：user-form | 广告导入：user-import
 * @param id 广告ID
 */
async function openDialog(type: any, row?: any) {
  dialog.visible = true;
  // 广告表单弹窗
  await loadDeptOptions();
  await loadRoleOptions();
  dialog.width = 800;
  if (row != undefined && row.adId != null) {
    if (type == "add-sp") {
      opType.value = 0;
    } else {
      opType.value = 1;
    }
    dialog.title = "广告跟进";

    Object.assign(formData, { ...row });
    Object.assign(formUserData, { ...row.carUser });
  } else {
    dialog.title = "新增广告";
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  广告表单：user-form | 广告导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    adFormRef.value.resetFields();
    adFormRef.value.clearValidate();

    formData.id = undefined;
    formData.status = "1";
  } else if (dialog.type === "user-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  adFormRef.value.validate((valid: any) => {
    if (valid) {
      const adId = formData.adId;
      loading.value = true;
      if (adId) {
        if (opType.value == 0) {
          formData.status = "1";
        } else {
          formData.status = "2";
        }
        updateAd(formData)
          .then(() => {
            ElMessage.success("修改广告成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除广告 */
function handleDelete(id?: number) {
  const adIds = [id || removeIds.value].join(",");
  if (!adIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除广告?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteAd(adIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 广告列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <!-- <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="全部" value="" />
                <el-option label="待联系" value="0" />
                <el-option label="投放" value="1" />
                <el-option label="完成" value="2" />
              </el-select>
            </el-form-item> -->

            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-image-viewer
          v-if="showViewer"
          :z-index="10000"
          @close="closeViewer"
          :url-list="listData"
        />

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              type="index"
              align="center"
              width="100"
            />
            <el-table-column
              key="username"
              label="用户名"
              align="center"
              prop="carUser.loginName"
            />
            <el-table-column
              label="用户昵称"
              align="center"
              prop="carUser.nickName"
            />
            <el-table-column label="头像" align="center" width="120">
              <template #default="scope">
                <span v-if="scope.row.carUser != null"
                  ><img
                    :src="scope.row.carUser.headImg"
                    style="height: 60px"
                    @click="getImg(scope.row.carUser.headImg)"
                /></span>
              </template>
            </el-table-column>

            <el-table-column label="电话" align="center" prop="telephone" />
            <el-table-column label="微信" align="center" prop="weChat" />

            <el-table-column
              label="车主认证"
              align="center"
              prop="carAuthBrand"
            />

            <el-table-column label="备注" align="center" prop="remark" />

            <!-- <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <span v-if="scope.row.status == 0"> 待联系 </span>
                <span v-if="scope.row.status == 1"> 投放 </span>
                <span v-if="scope.row.status == 2"> 完成 </span>
              </template>
            </el-table-column> -->

            <el-table-column
              label="申请时间"
              align="center"
              prop="createDate"
            />

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('add-sp', scope.row)"
                  ><i-ep-edit />跟进</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 广告新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="adFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input
            v-model="formUserData.loginName"
            readonly
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="formUserData.nickName"
            readonly
            placeholder="请输入用户昵称"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
